package org.alex.samples.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.alex.samples.javabean.AllStudent;
import org.alex.samples.javabean.AllSubject;
import org.alex.samples.javabean.CommonMessageResultVO;
import org.alex.samples.javabean.ExamSubjectVO;
import org.alex.samples.javabean.ExamTestVO;
import org.alex.samples.model.SubjectAndTestType;
import org.alex.samples.service.IExamSubjectService;
import org.alex.samples.service.IExamTestService;
import org.alex.samples.service.IExamUserService;
import org.alex.samples.service.IUserAndSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/teacher")
public class TeacherManageController {

	@Autowired
	private IExamSubjectService iExamSubjectService;

	@Autowired
	private IExamUserService iExamUserService;

	@Autowired
	private IUserAndSubjectService iUserAndSubjectService;

	@Autowired
	private IExamTestService iExamTestService;

	@ResponseBody
	@RequestMapping(value = "/getAllStudent")
	public AllStudent getAllStudent(Integer subjectId) {
		AllStudent allStudent = new AllStudent();
		allStudent.setAllUser(iExamUserService.findAll());
		allStudent.setSelectedUser(iUserAndSubjectService.getAllUserBySubject(subjectId));
		return allStudent;
	}

	@RequestMapping(value = "/manageSubject")
	public String manageSubject(Model model) {
		if (iExamSubjectService != null) {
			System.out.println(1);
		} else {
			System.out.println(2);
		}
		model.addAttribute("subject", iExamSubjectService.findAllExamSubject());
		return "teacher/subject";
	}

	@ResponseBody
	@RequestMapping(value = "/getAllSubject")
	public AllSubject getAllSubject(String userId) {
		AllSubject allSubject = new AllSubject();
		allSubject.setAllSubject(iExamSubjectService.findAllExamSubject());
		allSubject.setSelectedSubject(iUserAndSubjectService.getAllSubjectByUserId(userId));
		return allSubject;
	}

	@ResponseBody
	@RequestMapping(value = "/saveSubjectStudents")
	public String saveSubjectStudents(
			@RequestParam(required = false, name = "subjectStudents[]") String[] subjectStudents, Integer subjectId) {
		List<String> list = new ArrayList<String>();
		if (subjectStudents != null && subjectStudents.length != 0) {
			for (String student : subjectStudents) {
				list.add(student);
			}
		}
		try {
			iExamUserService.saveUserAndSubject(list, subjectId);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}

	@ResponseBody
	@RequestMapping(value = "/saveStudentSubjects")
	public String saveStudentSubjects(@RequestParam(name = "studentSubjects[]") String[] studentSubjects,
			String userId) {
		List<String> list = new ArrayList<String>();
		if (studentSubjects.length != 0 && studentSubjects != null) {
			for (String subject : studentSubjects) {
				list.add(subject);
			}
		}
		try {
			iUserAndSubjectService.savaUserAndSubjectByUserId(list, userId);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getSubjectById")
	public ExamSubjectVO getSubjectById(Integer subId) {
		ExamSubjectVO examSubjectVO = iExamSubjectService.getSubjectById(subId);
		return examSubjectVO;
	}

	@ResponseBody
	@RequestMapping(value = "/addSubject")
	public String addSubject(ExamSubjectVO examSubjectVO) {
		try {
			iExamSubjectService.addSubject(examSubjectVO);
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/editSubject")
	public String editSubject(ExamSubjectVO examSubjectVO) {
		try {
			iExamSubjectService.editSubject(examSubjectVO);
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}

	@RequestMapping(value = "/deleteSubject/{id}")
	public String deleteSubjectById(RedirectAttributes redirectAttributes, @PathVariable Integer id) {
		iExamSubjectService.deleteSubjectById(id);
		return "redirect:/teacher/toManageSubject";
	}

	@RequestMapping(value = "/getAllExamTest")
	public String getAllExamTest(Model model) {
		model.addAttribute("examTest", iExamTestService.findAll());
		return "teacher/examTest";
	}

	@ResponseBody
	@RequestMapping(value = "/getTestById", method = RequestMethod.POST)
	public ExamTestVO getTestById(Integer testId) {
		ExamTestVO examTestVO = iExamTestService.getTestById(testId);
		return examTestVO;
	}

	@ResponseBody
	@RequestMapping(value = "/deleteTest", method = RequestMethod.POST)
	public boolean deleteTest(Integer testId) {
		try {
			iExamTestService.deleteTest(testId);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@ResponseBody
	@RequestMapping(value = "/getSubjectAndTestType", method = RequestMethod.POST)
	public SubjectAndTestType getSelectInfo() {
		SubjectAndTestType subjectAndTestType = new SubjectAndTestType();
		subjectAndTestType.setExamTestTypes(iExamTestService.findAllExamTestType());
		subjectAndTestType.setSubjects(iExamTestService.findAllSubject());
		return subjectAndTestType;
	}

	@ResponseBody
	@RequestMapping(value = "/updateTest", method = RequestMethod.POST)
	public CommonMessageResultVO updateTest(@Valid ExamTestVO examTestVO, BindingResult bindingResult) {
		CommonMessageResultVO commonMessageResultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		commonMessageResultVO.setSuccess(false);
		if (bindingResult.hasErrors()) {
			List<ObjectError> errors = bindingResult.getAllErrors();
			for (ObjectError error : errors) {
				FieldError fieldError = (FieldError) error;
				messageMap.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			commonMessageResultVO.setMessageMap(messageMap);
			return commonMessageResultVO;
		}
		try {
			iExamTestService.updateTest(examTestVO);
			commonMessageResultVO.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			commonMessageResultVO.setMessageMap(messageMap);
		}
		return commonMessageResultVO;
	}

	@ResponseBody
	@RequestMapping(value = "/saveTest", method = RequestMethod.POST)
	public CommonMessageResultVO saveTest(@Valid ExamTestVO examTestVO, BindingResult bindingResult) {
		CommonMessageResultVO commonMessageResultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		commonMessageResultVO.setSuccess(false);
		if (bindingResult.hasErrors()) {
			List<ObjectError> errors = bindingResult.getAllErrors();
			for (ObjectError error : errors) {
				FieldError fieldError = (FieldError) error;
				messageMap.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			commonMessageResultVO.setMessageMap(messageMap);
			return commonMessageResultVO;
		}
		try {
			iExamTestService.addTest(examTestVO);
			commonMessageResultVO.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			commonMessageResultVO.setMessageMap(messageMap);
		}
		return commonMessageResultVO;
	}
}
